define(['treeView'], function() {
	'use strict';
	angular.module('backcenter.orgTree', [])
	.controller('orgTreeCtrl',['$rootScope', '$scope', '$uibModal' ,'BizData', '$ocLazyLoad', f])//控制器结束
    function f($rootScope,$scope, $uibModal, BizData, $ocLazyLoad) {
		var common = require('common');
		

		var Model = this;
		
		//接收调用的参数
//		Model.params = $stateParams; 
//		console.log('Model.params-->',Model.params);

	
		/**
		name:bizData#onNewCreateParam
		description: <b>[回调型事件]</b>业务新增数据创建新增参数事件，可以增加和修改用户自定义的参数
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"param" : {justep.Request.ActionParam} 新增参数对象,
			"defaultValues" : array - 新增行的默认值数组 ，数组的长度决定新增行数，数组中的对象是列的默认值
				defaultValues格式：
					[
						{列名:默认值,...},
						{列名:默认值,...},
						...
					]
		}
		</xmp>	
		@see justep.XData#newData
		@see justep.Request.ActionParam
		*/
		Model.dataOrgNewCreateParam = function(event) {
			event.param = {"billType": 'billType'};
		}

		/**
		name:bizData#onBeforeDelete
		description: <b>[回调型事件]</b>业务数据删除前
		@param {object} event 它的结构如下:<br/>
		{
			"source":组件的js对象
			,"cancel":可修改	，设置为true后中断当前delete动作
			,"deleteIDList":删除的行Id数组
		}
		*/
		Model.dataOrgBeforeDelete = function(event) {
			var sCreatorFID = event.source.getValue('sCreatorFID',event.deleteIDList[0]);
			if(sCreatorFID==event.deleteIDList[0]){
				event.cancel = true;
				alert('顶级机构，不能删除！');
			}
		}
		/**
		name:bizData#onAfterDelete
		description: <b>[回调型事件]</b>业务数据删除后
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"deleteIDList" : 删除的行Id数组
		}
		</xmp>	
		*/
		Model.dataOrgAfterDelete = function(event) {
//			alert('删除之后！')
		}

		Model.dataOrgAfterSave = function(event){
//			console.log('save.event-->',event);
		}

		/**
		name:bizData#onBeforeRefresh
		description: <b>[回调型事件]</b>业务数据刷新前
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"cancel" : 可修改，设置为true后中断当前刷新动作
		}
		</xmp>	
		*/
		Model.dataOrgBeforeRefresh = function(event){
			
		};
		
		/**
		name:bizData#onAfterRefresh
		description: <b>[回调型事件]</b>业务数据刷新后
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象
			"limit" : 页大小, 
			"offset" : 偏移,
			"success" : 是否成功刷新
		}
		</xmp>	
		*/
		Model.dataOrgAfterRefresh = function(event){
			
			var dataOrg = event.source;
			//展开第一个
			var rowID = dataOrg.getCurrentID();
			if(rowID!=null){
				dataOrg.expandRow(rowID);
			}
			
		}
		
		
		
		/**
		name:bizData#onIndexChanged
		description: <b>[回调型事件]</b>行记录变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
		"source" : 组件的js对象,
		"rowID" : 行Id,
		"rowIndex" : 行索引
		}
		</xmp>	
		*/
		Model.dataOrgIndexChanged = function(event) {
			
		}
		
		/**
		name:bizData#onDataChanged
		description: <b>[回调型事件]</b>数据发生变化（包括新增、刷新、删除、修改引起的变化），感知从data的变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
		"source" : 组件的js对象,
		"changedSource" ：触发变化的组件的js对象，当从data触发时返回从data对象,
		"selfChanged" : 是否自身变化，false：从data触发的变化,
		"type" : 触发变化的类型，包括：new、delete、refresh、valueChanged、clear，其他参数根据触发类型不同给出不同参数，参考onAfterNew等事件参数
		}
		</xmp>	
		*/
		Model.dataOrgDataChanged = function(event) {
			
		}
		
		/**
		name:bizData#onValueChanged
		description: <b>[回调型事件]</b>数据变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
		"source" : 组件的js对象,
		"column" : 关系,
		"rowIndex" : 行索引,
		"value" : 新值,
		"originalValue" : 旧值
		}
		</xmp>	
		*/
		//输入值变化，监视input的输入，ng-change
		Model.dataOrgValueChanged = function(event) {

			
			if(event.column=='sCode'){
				//整合自身全路径编码
				var rowID = event.source.getID(event.rowIndex);
				var sParent = event.source.getValue('sParent',rowID);
				var sCode = event.value;
				var sFCode = '';
				if(sParent==null){
					sFCode = sFCode + '/' + sCode;
				}else{
					sFCode = event.source.getValue('sFCode',sParent) + '/' + sCode;
				}
				event.source.setValue('sFCode',sFCode,rowID);
			}
			if(event.column=='sFCode'){
				//修改子节点的全路径编码
				var rowID = event.source.getID(event.rowIndex);
				var ids = $scope.dataOrg.getChildsIDs(rowID);
				for(var i=0;i<ids.length;i++){
					var sFCode = event.value + '/' + event.source.getValue('sCode',ids[i]);
					event.source.setValue('sFCode',sFCode,ids[i]);
				}
			}
			if(event.column=='sName'){
				//整合自身全路径名称
				var rowID = event.source.getID(event.rowIndex);
				var sParent = event.source.getValue('sParent',rowID);
				var sName = event.value;
				var sFName = '';
				if(sParent==null){
					sFName = sFName + '/' + sName;
				}else{
					sFName = event.source.getValue('sFName',sParent) + '/' + sName;
				}
				event.source.setValue('sFName',sFName,rowID);
			}
			if(event.column=='sFName'){
				//修改子节点的全路径名称
				var rowID = event.source.getID(event.rowIndex);
				var ids = $scope.dataOrg.getChildsIDs(rowID);
				for(var i=0;i<ids.length;i++){
					var sFName = event.value + '/' + event.source.getValue('sName',ids[i]);
					event.source.setValue('sFName',sFName,ids[i]);
				}
			}

			
			if(event.column=='sID'){
				//整合自身全路径编码
				var rowID = event.source.getID(event.rowIndex);
				var sParent = event.source.getValue('sParent',rowID);
				var sOrgKindID = event.source.getValue('sOrgKindID',rowID);
				var sID = event.value;
				var sFID = '';
				if(sParent==null){
					sFID = sFID + '/' + sID + '.' + sOrgKindID;
				}else{
					sFID = event.source.getValue('sFID',sParent) + '/' + sID + '.' + sOrgKindID;
				}
				event.source.setValue('sFID',sFID,rowID);
			}
			if(event.column=='sFID'){
				//修改子节点的全路径编码
				var rowID = event.source.getID(event.rowIndex);
				var ids = $scope.dataOrg.getChildsIDs(rowID);
				for(var i=0;i<ids.length;i++){
					var sFID = event.value + '/' + event.source.getValue('sID',ids[i]) + '.' + event.source.getValue('sOrgKindID',ids[i]);
					event.source.setValue('sFID',sFID,ids[i]);
				}
			}

			
		}
		
		
		//定义页面级别的变量
//		var systemCode; //系统代码
//		var billType = 'ITEM';
//		var billTypeName = "";
//		var flowType = 0;
//		var autoCode; //是否自动编码
//		var revOpay; //入库出库
//		var direction;
//		var costingCode; //影响成本码
//		var origin;
//		var originName = "";
//		var billNo = "";


		/**
		name:bizData#onBeforeNew
		description: <b>[回调型事件]</b>业务数据新增前
		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
		*/
		Model.dataOrgBeforeNew = function(event) {
			
		};
		
		
		/**
		* name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
		* 
		* @param event
		*            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
		*/
		Model.dataOrgAfterNew = function(event){
//			event.source.setValue('sCreatorFID', event.data.person.userId, event.id);	
//			event.source.setValue('cUsercode', event.data.person.cUsercode, event.id);	
//			event.source.setValue('cUsername', event.data.person.cUsername, event.id);	
			
			//整合自身全路径编码
			var sID = event.id;
			var sParent = event.source.getValue('sParent',sID);
			var sOrgKindID = event.source.getValue('sOrgKindID',sID);
			var sFID = '';
			if(sParent==null){
				sFID = '/' + sID + '.' + sOrgKindID;
			}else{
				sFID = event.source.getValue('sFID',sParent) + '/' + sID + '.' + sOrgKindID;
				//展开父节点
				$scope.dataOrg.expandRow(sParent);
			}
			event.source.setValue('sFID',sFID,sID);

		}
		
		
		
		///////////////////按钮组开始///////////////////////////////////////////////////
		//新建（跟）
		Model.addRoot = function(){
			
//			alert('开设子公司，须在用户中心进行操作！');
//			return;

			//树形专用
			var sNodeKind = 'nkLeaf';
			var sParent = null;
			var sFID = null;
			var sLevel = 1;
			var sSequence = null;
			var sValidState = 1;
			var sOrgKindID = 'ogn'
			
//			sParent = null;
//			sFID = null;
//			sLevel = 1;
			var rootCount = $scope.dataOrg.getRoots().length;
			sSequence = '/' + common.preZeroFill(rootCount + 1,3);
			
			var options = {
					index : $scope.dataOrg.rows.length,
					defaultValues : [
					                 {
						            	 
					                	 sParent:sParent
					                	 ,sNodeKind:sNodeKind
					                	 ,sLevel:sLevel
					                	 ,sSequence:sSequence
					                	 ,sValidState:sValidState
					                	 ,sOrgKindID:sOrgKindID
						            	 ,sCreatorFID: ':getCurrentPersonID()'
						            	 
						            	 ,version:0
					                	 }
//					                 ,{sName:'a2',sCode:'b2'}
					                 ]
			};    

			var ids = $scope.dataOrg.newData(options);
			//设置全路径ID
//			$scope.dataOrg.rows[$scope.dataOrg.currentIndex].sFID.value = (sFID==null?'':sFID) + '/' + ids[0];
			
		};
		
		
		//新建子节点
		Model.addChild = function(sOrgKindID){
			//树形专用
			var sNodeKind = 'nkLeaf';
			var sParent = null;
			var sFID = null;
			var sLevel = 1;
			var sSequence = null;
			var sValidState = 1;
//			var sOrgKindID = 'ogn'
			
			if($scope.dataOrg.currentIndex== -1){return;}
			sParent = $scope.dataOrg.currentID;
			var parentIndex = $scope.dataOrg.getIndex(sParent);
			sFID = $scope.dataOrg.rows[$scope.dataOrg.currentIndex].sFID.value;
			sLevel = $scope.dataOrg.rows[$scope.dataOrg.currentIndex].sLevel.value + 1;
			var childCount = $scope.dataOrg.getChilds(sParent).length;
			
			sSequence =$scope.dataOrg.rows[$scope.dataOrg.currentIndex].sSequence.value + '/' + common.preZeroFill(childCount + 1,3);
			
			$scope.dataOrg.rows[$scope.dataOrg.currentIndex].sNodeKind.value = null;			
			
			var childrenCount = $scope.dataOrg.getChildren(sParent).length;
			var options = {
					index : parentIndex + childrenCount + 1,
					defaultValues : [
					                 {
					                	 sParent:sParent
					                	 ,sNodeKind:sNodeKind
					                	 ,sLevel:sLevel
					                	 ,sSequence:sSequence
					                	 ,sValidState:sValidState
					                	 ,sOrgKindID:sOrgKindID
						            	 ,sCreatorFID: ':getCurrentPersonID()'
						            	 
						            	 ,version:0
					                	 }
//					                 ,{sName:'a2',sCode:'b2'}
					                 ]
			};    

			var ids = $scope.dataOrg.newData(options);
			//设置全路径ID
//			$scope.dataOrg.rows[$scope.dataOrg.currentIndex].sFID.value = (sFID==null?'':sFID) + '/' + ids[0];
		}
		
		/*
		//新建兄弟节点
		Model.addBrother = function(){
			//树形专用
			var sNodeKind = 'nkLeaf';
			var sParent = null;
			var sFID = null;
			var sLevel = 1;
			var sSequence = null;
			var sValidState = 1;
			
			if($scope.dataOrg.currentIndex== -1){return;}
			sParent =  $scope.dataOrg.rows[$scope.dataOrg.currentIndex].sParent.value;
			if(sParent==null){return;}
			var parentIndex = $scope.dataOrg.getIndex(sParent);
			sFID = $scope.dataOrg.rows[parentIndex].sFID.value;
			sLevel = $scope.dataOrg.rows[$scope.dataOrg.currentIndex].sLevel.value;
			var childCount = $scope.dataOrg.getChilds(sParent).length;
			sSequence =$scope.dataOrg.rows[parentIndex].sSequence.value + '/' + common.preZeroFill(childCount + 1,3);
			
//			$scope.dataOrg.rows[$scope.dataOrg.currentIndex].sNodeKind.value = null;			
			
			var childrenCount = $scope.dataOrg.getChildren(sParent).length;
			var options = {
					index : parentIndex + childrenCount + 1,
					defaultValues : [
					                 {
						            	 
					                	 sParent:sParent
					                	 ,sNodeKind:sNodeKind
					                	 ,sLevel:sLevel
					                	 ,sSequence:sSequence
					                	 ,sValidState:sValidState
						            	 
						            	 ,version:0
					                	 }
//					                 ,{sName:'a2',sCode:'b2'}
					                 ]
			};    

			var ids = $scope.dataOrg.newData(options);
			//设置全路径ID
//			$scope.dataOrg.rows[$scope.dataOrg.currentIndex].sFID.value = (sFID==null?'':sFID) + '/' + ids[0];
		}
		*/

		/*
		//新建人员
		//新建子节点
		Model.newPerson = function(){
			//首先获取当前组织ID
			var orgID = $scope.dataOrg.getCurrentID();
			if(orgID==null || orgID==''){
				return;
			}
			
			var sOrgKindID = $scope.dataOrg.getValue('sOrgKindID',orgID);
			if(sOrgKindID=='psm'){
				return;
			}
			
			//打开对话框
			var options = {};
			
			options.recordState = 'new';
			options.id = '';

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: 'lg',
	            templateUrl: $rootScope.getProjectName() + '/backcenter/person/single',  
	            controller: 'personSingleCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '新建'; }
                    ,loadCtrl : $ocLazyLoad.load('js/person/single')
		        }
	        });  
	        //模态窗口打开之后执行的函数
	        modalInstance.opened.then(function(){  
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (result) {  
	            //成功关闭窗口
	        	//console.log('result-->',result);
         		
         		var data = {};
        		data.orgID = orgID;
         		data.data = result.data[0];
             	
    			//提交保存
				$.ajax({
		            type: "POST",
		            async : false,
		            url: $rootScope.getProjectName() + "/backcenter/org/tree/newPersonMember",
		            data: JSON.stringify(data),// "{}",
		            contentType: "application/json; charset=utf-8",
		            dataType: "json",
//		            processData: false,
		            success: function (data) {
		                // Play with returned data in JSON format
						if(data.code==0){
							var index = $scope.dataOrg.getCurrentIndex();
		    				$scope.dataOrg.refreshData();
//		    				$scope.dataOrg.refreshPageData(index);
		    				
		    				$scope.dataOrg.expandRow(orgID);
						}else{
							alert(data.status);
						}
		            },
		            error: function (msg) {
//		                alert(msg.responseText);
	    				alert('操作失败，可能存在网络问题！')
		            }
		        });

	        }, function (reason) {  
	        	
	        });  
			
		};
		*/

		//分配人员（普通员工）
		//新建子节点
		Model.addPerson = function(){
			//首先获取当前组织ID
			var orgID = $scope.dataOrg.getCurrentID();
			if(orgID==null || orgID==''){
				return;
			}
			
			var sOrgKindID = $scope.dataOrg.getValue('sOrgKindID',orgID);
			if(sOrgKindID=='psm'){
				return;
			}
			
			var options = {};
			options.recordState = 'none';
			//获取当前组织的创始人
			options.id = $rootScope.topMyOgn.sID;
			
//			var modalInstance = systemService.openPersonOrgCodeDialog(options);
			
	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: '',
	            templateUrl: $rootScope.getProjectName() + '/backcenter/person/selectSingle',  
	            controller: 'personSelectSingleCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '选择'; }
                    ,loadCtrl : $ocLazyLoad.load('js/person/selectSingle.js')
		        }
	        });  
	        
			/*
	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: '',
	            templateUrl: $rootScope.getProjectName() + '/backcenter/selectEmployee/selectSingle',  
	            controller: 'fileEmployeeSelectSingleCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '选择'; }
                    ,loadCtrl : $ocLazyLoad.load('js/0_selectEmployee/selectSingle.js')
		        }
	        });  
	        */
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
//	             		alert(returnData[i].sID+'-->'+returnData[i].sName);
//	             		var personID = returnData[i].personID;
	             		var personID = returnData[i].sID;
	             		var personCode = returnData[i].sCode;
	             		var personName = returnData[i].sName;
	        			if(personID!=null && personID!=''){
	        				//分配人员
	                 		
	                 		var data = {};
	                		data.orgID = orgID;
	                 		data.personID = personID;
	                 		data.personCode = personCode;
	                 		data.personName = personName;
	    	             	
	    	    			//提交保存
	                 		
	    					var response = $.ajax({
	    			            type: "POST",
	    			            async : false,
	    			            url: $rootScope.getProjectName() + "/backcenter/org/tree/addPersonMember",
	    			            data: JSON.stringify(data),// "{}",
	    			            contentType: "application/json; charset=utf-8",
	    			            dataType: "json",
//	    			            processData: false,
	    			            success: function (data) {
	    			                // Play with returned data in JSON format
	    			            },
	    			            error: function (msg) {
//	    			                alert(msg.responseText);
	    			            }
	    			        });

	    					if (response.readyState == 4 && response.status == 200) {
	    						var index = $scope.dataOrg.getCurrentIndex();
	    	    				$scope.dataOrg.refreshData();
//	    	    				$scope.dataOrg.refreshPageData(index);
	    	    				
	    	    				$scope.dataOrg.expandRow(orgID);
	    	    				return 0;
	    	    			}else{
	    	    				alert('保存失败！')
	    	    				return -1;
	    	    			}
	    	    			
	        				
	        			}
	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		}
		
		//添加创始人
		//新建子节点
		Model.addFounder = function(){
			//首先获取当前组织ID
			var orgID = $scope.dataOrg.getCurrentID();
			if(orgID==null || orgID==''){
				return;
			}
			
			var sOrgKindID = $scope.dataOrg.getValue('sOrgKindID',orgID);
			if(sOrgKindID=='psm'){
				return;
			}
			
			var personID = '';
			
			var data = {};
    		data.orgID = orgID;
     		data.personID = personID;
         	
			//提交保存
     		
			var response = $.ajax({
	            type: "POST",
	            async : false,
	            url: $rootScope.getProjectName() + "/backcenter/org/tree/addFounderMember",
	            data: JSON.stringify(data),// "{}",
	            contentType: "application/json; charset=utf-8",
	            dataType: "json",
//	            processData: false,
	            success: function (data) {
	                // Play with returned data in JSON format
	            },
	            error: function (msg) {
//	                alert(msg.responseText);
	            }
	        });

			if (response.readyState == 4 && response.status == 200) {
				var index = $scope.dataOrg.getCurrentIndex();
				$scope.dataOrg.refreshData();
//				$scope.dataOrg.refreshPageData(index);
				
				$scope.dataOrg.expandRow(orgID);
				return 0;
			}else{
				alert('保存失败！')
				return -1;
			}
			
			
		};
		
		//修改
		Model.edit = function(){
			$scope.dataOrg.editData();
		}
		
		//保存
		Model.save = function() {
			$scope.dataOrg.saveData();
		}
		
		//取消保存
		Model.saveCancel = function() {
			/*
			if($scope.dataOrg.recordState == 'new'){
				$scope.dataOrg.loadPageData();
			}else{
				$scope.dataOrg.refreshPageData();
			}
			*/
//			$scope.dataOrg.refreshData();
			$scope.dataOrg.editCancel();
			
		}
		
		//直接删除
		Model.remove = function() {
			 if($scope.dataOrg.directDeleteMode){
				 if($scope.dataOrg.deleteData($scope.dataOrg.getCurrentID())==0){
					 $scope.dataOrg.refreshData();
				 }
			 }else{
				 $scope.dataOrg.removeData($scope.dataOrg.getCurrentID());
				 $scope.dataOrg.editData();
			 }
		};
		
		//刷新
		Model.refresh = function() {
			$scope.dataOrg.refreshData();
		}
		
		//排序
		Model.sort = function(fParent) {
			var parentID = null;
			if(fParent!='root'){
				parentID = $scope.dataOrg.getCurrentID();
			}

			var options = {};
			
			options.recordState = 'none';
			options.id = $rootScope.topMyOgn.sID;
			options.parentID = parentID;

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: '',
	            templateUrl: $rootScope.getProjectName() + '/backcenter/org/sortView',  
	            controller: 'orgSortCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '选择'; }
                    ,loadCtrl : $ocLazyLoad.load('js/org/sort')
		        }
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
				
				//装配参数
				var data = new Object();
				data.parentID = parentID;
				data.ids = returnData;
				
				var response = $.ajax({
		            type: "POST",
		            async : false,
		            url: $rootScope.getProjectName() + "/backcenter/org/sort",
		            data: JSON.stringify(data),// "{}",
		            contentType: "application/json; charset=utf-8",
		            dataType: "json",
//		            processData: false,
		            success: function (data) {
		                // Play with returned data in JSON format
		            },
		            error: function (msg) {
//		                alert(msg.responseText);
		            }
		        });

				if (response.readyState == 4 && response.status == 200) {
    				$scope.dataOrg.refreshPageData();
    				if(parentID!=null){
        				$scope.dataOrg.expandRow(parentID);
    				}
    				return 0;
    			}else{
    				alert('操作失败！')
    				return -1;
    			}
				
				

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
		}

		
		
		///////////////////按钮组结束///////////////////////////////////////////////////
		
		
		
		

		
		////////////////////////////////////////////////////////////////////////////////////////
		
		//打开对话框（设置人员主岗）
		Model.triggerMainOrgIDClick = function(){
			/*
			var rowID = $scope.dataOrg.getCurrentID();
			var personID = $scope.dataOrg.getValue('sPersonID',rowID);
			var options = {};
			
			options.recordState = 'none';
			options.ognID = $rootScope.topMyOgn.sID
			
			var modalInstance = systemService.openPsmIDDialog(options);

			//模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;

	             if(returnData.length==1){
	            	 
	            	 var data = new Object();
	            	 data.id = options.id;
	            	 //
	            	 data.orgID = returnData[0].sID.split("@")[0];
	            	 var response = securityService.getUpdateMainOrgByID(data);
	 				response.success(function(data, status, headers, config) {
	    				$rootScope.addAlert('success','操作成功！');
	 					
	 				});
	 				response.error(function(data, status, headers, config) {
	    				var msg = new Object();
	    				msg.title = '错误';
	    				msg.kind = 'info';//confirm:显示取消按钮
	    				msg.type = 'danger';
	    				msg.statusMsg = '操作失败！';
	    				
	    				var dlg = systemService.dialogMsg(msg);
	 				});
	 				
	    			if (response.readyState == 4 && response.status == 200) {
	    				$rootScope.addAlert('success','操作成功！');
	    			}else{
	    			}
	            	 
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			*/
		};
		
		
		
		var options = {};
		options.container = Model;
		options.concept = 'SaOporg';
		options.name = 'dataOrg';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
		options.creater = '/backcenter/org/tree/create';
		options.reader = '/backcenter/org/tree/query';
		options.writer = '/backcenter/org/tree/save';
		options.deleter = '/backcenter/org/tree/delete';
		options.idColumnDefine = "sID";
		options.idColumnName = "sID";
		options.isTree = true;
		options.parentRelation = 'sParent';
		options.nodeKindRelation = 'sNodeKind';
		options.nodeLevelRelation = 'sLevel';
		options.nodeSortRelation = "sSequence";
		options.pathRelation = 'sFID';
		options.directDeleteMode = false;
   		options.limit = -1;
		options.orderBy = 'sSequence ASC';
		
		options.onIndexChanging = null;
		options.onIndexChanged = Model.dataOrgIndexChanged;
		options.onBeforeNew = Model.dataOrgBeforeNew;
		options.onAfterNew = Model.dataOrgAfterNew;
		options.onBeforeDelete = Model.dataOrgBeforeDelete;
		options.onAfterDelete = Model.dataOrgAfterDelete;
		options.onValueChanged = Model.dataOrgValueChanged;
		options.onDataChanged = Model.dataOrgDataChanged;
		options.onAfterSave = Model.dataOrgAfterSave;
		options.onAfterRefresh = Model.dataOrgAfterRefresh;
		options.onNewCreateParam = Model.dataOrgNewCreateParam;
		
		$scope.dataOrg = new BizData(options);

		//监视对象中的所有变动
		$scope.dataOrg.deregRows = $scope.$watch('dataOrg.rows',$scope.dataOrg.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		//////////////////////////////////////////////
    	
    	if($rootScope.checkTopMyOgn()==true){
    		//增加过滤条件
    		$scope.dataOrg.filter = "SaOporg.sFID like '%" + $rootScope.topMyOgn.sID + "%'";
//    		$scope.dataOrg.filter = "SaOporg.sCreatorFID = '" + $rootScope.topMyOgn.sID + "'";
    		$scope.dataOrg.refreshData();
    	}
	    
	    ///////////////////////////页面级////////////////////////////////////////
		//返回
		Model.goBack = function(event) {
			window.history.go(-1);
		}
	    ///////////////////////////页面级////////////////////////////////////////
	
		
	    return Model;

	}	
	
});
